package com.car.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.entity.Vehicle;
import com.car.mapper.VehicleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 车辆服务
 *
 * @author Car System
 */
@Service
@RequiredArgsConstructor
public class VehicleService {

    private final VehicleMapper vehicleMapper;

    /**
     * 分页查询车辆（带客户信息）
     */
    public IPage<Vehicle> page(Integer current, Integer size, String keyword) {
        Page<Vehicle> page = new Page<>(current, size);
        return vehicleMapper.selectVehiclePageWithCustomer(page, keyword);
    }

    /**
     * 根据客户ID查询车辆列表
     */
    public List<Vehicle> listByCustomerId(Long customerId) {
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Vehicle::getCustomerId, customerId)
                .orderByDesc(Vehicle::getCreateTime);
        return vehicleMapper.selectList(wrapper);
    }

    /**
     * 根据ID查询车辆
     */
    public Vehicle getById(Long id) {
        return vehicleMapper.selectById(id);
    }

    /**
     * 新增车辆
     */
    public void save(Vehicle vehicle) {
        // 检查车牌号是否已存在
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Vehicle::getPlateNumber, vehicle.getPlateNumber());
        if (vehicleMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("该车牌号已存在");
        }
        
        vehicleMapper.insert(vehicle);
    }

    /**
     * 更新车辆
     */
    public void update(Vehicle vehicle) {
        // 检查车牌号是否被其他车辆使用
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Vehicle::getPlateNumber, vehicle.getPlateNumber())
                .ne(Vehicle::getId, vehicle.getId());
        if (vehicleMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("该车牌号已被其他车辆使用");
        }
        
        vehicleMapper.updateById(vehicle);
    }

    /**
     * 删除车辆
     */
    public void delete(Long id) {
        vehicleMapper.deleteById(id);
    }

    /**
     * 统计车辆总数
     */
    public Long count() {
        return vehicleMapper.selectCount(null);
    }
}

